#include <STC15F2K60S2.H>
#include "Seg.h"
#include "Tim.h"
#include "Key.h"
#include "iic.h"
#include "stdio.h"
#include "Ptim.h"
#include "LED.h"
//对adda的使用，注意刷新时间，频率测量，注意灯的使用
//灯的问题
unsigned char pucSeg_Buf[9],pucSeg_Code[8],ucSeg_Pos;
unsigned char ucKey_Dly,ucKey_Old;
unsigned int ucSeg_Dly;
unsigned long ulms;
unsigned char ucpcf_U;
unsigned char ucState,ucSeg_Flag,ucU_Flag,ucLed_Flag;
unsigned int ucpcf_Val;
unsigned char ucLed;
unsigned int uccount;
void Key_Proc(void) ;
void Seg_Proc(void);
void Led_Proc(void);//这个函数用来改变ucled的值，显示函数在定时器里使用
void main(){
	Cls_Peripheral() ;
	Timer1Init();
	Timer0Init();
	while(1){
		Key_Proc();
		Seg_Proc();
		Led_Proc();
}
}
void Time_1(void) interrupt 3 //定时器1中断函数
{ 
	 ulms++; 
	 if(!(ulms % 1000)) 
	 { 
		 uccount=(TH0<<8)+TL0;
		 TH0=0;
		 TL0=0;
	} 
	 Led_Disp(ucLed) ;//数码管刷新太快会影响灯的亮度   放在计时器里，找能改变P0的值的
	 if(++ucKey_Dly==10) ucKey_Dly=0;
	 if(++ucSeg_Dly==500) ucSeg_Dly=0;
	 Seg_Disp(pucSeg_Code, ucSeg_Pos);
	if(++ucSeg_Pos==8) ucSeg_Pos=0;
}
void Key_Proc(void) 
{ 
	 unsigned char ucKey_Val, ucKey_Down, ucKey_Up; 
	 if(ucKey_Dly) return; 
		ucKey_Dly = 1; 
	 ucKey_Val = Key_Read(); 
	 ucKey_Down = ucKey_Val & (ucKey_Old ^ ucKey_Val); 
	 ucKey_Up = ~ucKey_Val & (ucKey_Old ^ ucKey_Val); 
	 ucKey_Old = ucKey_Val; 
	switch(ucKey_Down){
		case 4:
			ucState^=1;
			break;
		case 5:
			ucU_Flag^=1;
			break;
		case 8:
			ucLed_Flag^=1;
			break;
		case 9:
			ucSeg_Flag^=1;
			break;
	}
}
void Seg_Proc(void){
	if(ucSeg_Dly) return;
		ucSeg_Dly=1;
	ucpcf_U=PCF8591_Adc(); //模数和数模转换对应刷新时间可以在数码管按键等函数对应实现
	if(!ucU_Flag)
			PCF8591_Dac(102); //电压对应二进制要*51
		else
			PCF8591_Dac(ucpcf_U);
	if(!ucSeg_Flag){
			if(ucState){
		sprintf(pucSeg_Buf,"F %6d",uccount);
	}
	else{
		sprintf(pucSeg_Buf,"U    %03.2f",ucpcf_U/51.0);//影响灯是数码管显示影响
	}
	}
	else
		sprintf(pucSeg_Buf,"        ");
	Seg_Tran(pucSeg_Buf, pucSeg_Code);
}
void Led_Proc(void){//一般数码管不会影响，就正常实现就好
	if(!ucLed_Flag) {
		if(ucState){
		ucLed&=~1;
		ucLed|=2;
	}
	else{
		ucLed&=~2;
		ucLed|=1;
	}
	ucpcf_Val=ucpcf_U*100/51;
	if(((ucpcf_Val>=250)&&(ucpcf_Val<350))||(ucpcf_Val<150)){//要使用单个条件结合，不能使用结合条件：0<a<4,不然语句判断不行
		ucLed&=~4;
	}
	else {
			ucLed|=4;
	}
	if((uccount<1000)||((uccount>=5000)&&(uccount<=10000))){
		ucLed&=~8;
	}
	else{
		ucLed|=8;
	}
	if(!ucU_Flag){
		ucLed&=~16;
	}
	else{
		ucLed|=16;
	}
	}
	else 
		ucLed=0;
}